package com.woniuxy.run.user.utils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 对用户请求功能的封装
 */

@Component
public class Request {

    private static RedisTemplate<String, Object> redisTemplate;

    @Resource(name = "redisTemplate")
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        Request.redisTemplate = redisTemplate;
    }

    // 获取token
    public static String getToken() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return "";
        }
        String key = request.getHeader("token");
        return key;
    }

    // 获取请求对象
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    // 获取响应对象
    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    // 获取登陆用户信息
    public static String getUsername() {
        HttpServletRequest request = getRequest();
        String token = request.getHeader("token");
        String result = "";
        ValueOperations operations = redisTemplate.opsForValue();
        result = (String) operations.get(token + "username");
        return result;
    }

    // 获取登陆用户名称
    public static String getNickname() {
        HttpServletRequest request = getRequest();
        String token = request.getHeader("token");
        String result = "";
        ValueOperations operations = redisTemplate.opsForValue();
        result = (String) operations.get(token + "nickname");
        return result;
    }
}
